package com.zh.zcy.filter;

import com.zh.zcy.entity.User;
import com.zh.zcy.untils.UserContextUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {

    //Controller方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //没有办法直接获取到json流中的请求参数
        System.out.println("MyInterceptor的preHandle方法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor的postHandle方法");
    }

    //整个请求执行结束后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor的afterCompletion方法");
        User u = UserContextUtil.getUser();
        System.out.println("拦截器clear之前"+u.toString());
        UserContextUtil.clear();
        //这里还是打印之前的对象，clear只是清除了ThreadLocal的key，没有清除value，下面导致又用旧的key获取value
        System.out.println("拦截器clear之后"+u.toString());
        User newU = UserContextUtil.getUser();
        //这里打印User{id=null, name='null', age=0}，说明ThreadLocal被清除了
        System.out.println("重新getUser:"+newU.toString());

    }
}
